package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.service.MemberMobileService;
import com.xrit.sunnyday.service.ReportService;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberMobileService memberMobileService;

    @Reference
    private ReportService reportService;

    /**
     * 会员统计，条形图
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        //建一个集合，存去年的12个月
        List<String> months = new ArrayList<>();
        //使用java中的calendar日期对象操作日期
        Calendar calendar = Calendar.getInstance();
        //Calendar.YEAR当前年，-1去年
        calendar.add(Calendar.YEAR,-1);
        //构建12个月的数据
        for (int i = 0; i < 12; i++) {
            //Calendar.MONTH当前月，1 = +1 ，每次加一个月
            calendar.add(Calendar.MONTH,1);
            //获取每个月的日期
            Date calendarTime = calendar.getTime();
            //把日期转换成我们需要的日期格式
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dataString = format.format(calendarTime);
            //添加到集合
            months.add(dataString);
        }

        //建一个集合存储去年每个月的会员注册数量
        List<Integer> memberCount = memberMobileService.getMemberReport(months);

        //把日期和会员数量存储到MAP返回到前端
        //前端数组，后端用集合
        //因为前端需要日期和会员数量，两个集合泛行不一样，我们存储到MAP
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("months",months);
        resultMap.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,resultMap);
    }

    /**
     * 套餐统计，饼状图
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        //前端需要数组套对象的数据，后端查询套餐name和被下单的次数存到map，因为有多个套餐所以list套map
        List<Map<String,Object>> setmealCount = memberMobileService.getSetmealReport();
        //遍历list拿到map里面的套餐name，添加到一个新的集合
        List<String> setmealNames = new ArrayList<>();
        for (Map<String,Object> map : setmealCount) {
            String name = (String) map.get("name");
            setmealNames.add(name);
        }

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("setmealCount",setmealCount);
        resultMap.put("setmealNames",setmealNames);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,resultMap);
    }

    /**
     * 运营数据统计
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        Map<String,Object> reportData = reportService.getBusinessReportData();
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,reportData);
    }

    /**
     * 导出运营统计数据报表
     * 1.获取到这个表的所有数据（已完成）
     * 2.读取Excel模板
     * 3.将数据写入到Excel
     * 4.导出，使用IO流将Excel下载
     */
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse res){
        //获取运营数据统计
        Map<String, Object> reportData = reportService.getBusinessReportData();
        //获取模板路径
        String path = req.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        try(
                FileInputStream is = new FileInputStream(path);
                OutputStream os = res.getOutputStream();
                Workbook wk = new XSSFWorkbook(is);
                ){

            XSSFSheet st = (XSSFSheet) wk.getSheetAt(0);
            //日期
            st.getRow(2).getCell(5).setCellValue(reportData.get("reportDate").toString());
            // =================== 会员统计 ======================
            //新增会员数
            st.getRow(4).getCell(5).setCellValue((Integer)reportData.get("todayNewMember"));
            //总会员数
            st.getRow(4).getCell(7).setCellValue((Integer)reportData.get("totalMember"));
            //本周新增会员数
            st.getRow(5).getCell(5).setCellValue((Integer)reportData.get("thisWeekNewMember"));
            //本月新增会员数
            st.getRow(5).getCell(7).setCellValue((Integer)reportData.get("thisMonthNewMember"));

            // ===============  预约统计 ===================
            //今日预约数
            st.getRow(7).getCell(5).setCellValue((Integer)reportData.get("todayOrderNumber"));
            //今日到诊数
            st.getRow(7).getCell(7).setCellValue((Integer)reportData.get("todayVisitsNumber"));
            //本周预约数
            st.getRow(8).getCell(5).setCellValue((Integer)reportData.get("thisWeekOrderNumber"));
            //本周到诊数
            st.getRow(8).getCell(7).setCellValue((Integer)reportData.get("thisWeekVisitsNumber"));
            //本月预约数
            st.getRow(9).getCell(5).setCellValue((Integer)reportData.get("thisMonthOrderNumber"));
            //本月到诊数
            st.getRow(9).getCell(7).setCellValue((Integer)reportData.get("thisMonthVisitsNumber"));

            // ============== 热门套餐 ==================
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) reportData.get("hotSetmeal");
            int row = 12;
            for (Map<String, Object> map : hotSetmeal) {
                st.getRow(row).getCell(4).setCellValue((String) map.get("name"));
                st.getRow(row).getCell(5).setCellValue((Long)map.get("setmeal_count"));
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                st.getRow(row).getCell(6).setCellValue(proportion.doubleValue());
                st.getRow(row).getCell(7).setCellValue((String) map.get("remark"));
                row++;
            }

            String filename = "运营统计数据报表.xlsx";
            // 解决下载的文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");

            // 设置头信息，告诉浏览器，是带附件的，文件下载
            res.setHeader("Content-Disposition","attachement;filename=" + filename);
            // 设置内容体的文件格式是excel
            res.setContentType("application/vnd.ms-excel");
            wk.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
